package com.surprise.common.util;

public class StringTool {
	private static char[] TOLETTER = new char[] {'Y','G','K','H','N','T','Q','S','A','E'};
	
	public static int StringToNum(String str,int d_num) {
		if(str==null||str.isEmpty()) {
			return d_num;
		}else {
			try {
				d_num=Integer.parseInt(str); //报错
				return d_num;
			}catch (NumberFormatException e){
				//System.out.println(e); 
				return d_num;
			}
		}
	}
	
	public static String NumToString(int num, int num_size, String start_str) {
		StringBuffer sb = new StringBuffer(start_str);
		String str = String.valueOf(num);
		int addnum = num_size - str.length();
		for(int i=0; i<addnum; i++) {
			sb.append("0");
		}
		sb.append(str);
		return sb.toString();
	}
	//用户根据ID转成邀请码
	public static String NumToLetter(int num) {
		StringBuffer sb = new StringBuffer();
		String num_str = NumToString(num,6,"");
		for(int i=0;i<num_str.length();i++) {
			int b = num_str.charAt(i) - '0';
			sb.append(TOLETTER[b]);
		}
		//System.out.print("-------------------------------"+LetterToNum(sb.toString()));
		return sb.toString();
	}
	
	public static int LetterToNum (String letter_str) {
		if(letter_str==null||letter_str.isEmpty()) {
			return 0;
		}
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<letter_str.length();i++) {
			char letter_char = letter_str.charAt(i);
			for(int j=0;j<TOLETTER.length;j++) {
				if(letter_char == TOLETTER[j]) sb.append(j);
			}
		}

		return StringToNum(sb.toString(),0);
	}
	
	public static String truncateStr(String str, int len) {
		if(str==null || str.equals("") || len==0)
		{
			return "";
		}
		char[] charArr = str.toCharArray();
		int count = 0;
		StringBuilder sb = new StringBuilder("");
		for(char c :charArr){
			if(count<len){
				int add_count = String.valueOf(c).getBytes().length;
				if(add_count>1&&count+1==len){
					return sb.toString();
				}else{
					count = count+add_count;
					sb.append(c);
				}
			}else{
				break;
			}
		}
		return sb.toString();
	}


	 
}
